local UI = UI

local ALL_EVENTS = {}

UI.events = {}

function UI.RegisterEvent(frame, name)
	assert(type(name) == "string" or name == ALL_EVENTS)
	local t = UI.events[name]
	if not t then
		t = {}
		UI.events[name] = t
	end
	t[frame] = true
end

function UI.UnregisterEvent(frame, name)
	local t = UI.events[name]
	if t then
		t[frame] = nil
	end
end

function UI.IsEventRegistered(frame, name)
	local t = UI.events[name]
	return t and t[frame]
end

function UI.RegisterAllEvents(frame)
	UI.RegisterEvent(frame, ALL_EVENTS)
end

function UI.UnregisterAllEvents(frame)
	UI.UnregisterEvent(frame, ALL_EVENTS)
	for _, t in pairs(UI.events) do
		t[frame] = nil
	end
end

function UI.BroadcastEvent(event, ...)
	if event == "PLAYER_LOGIN" then
		UI.playerLoggedIn = true
	end
	local sent = {}
	log("II EVENT_DISPATCH: %s", event)
	local t = UI.events[event]
	if t then
		for frame in pairs(t) do
			UI.CallScript(frame, "OnEvent", event, ...)
			sent[frame] = true
		end
	end
	t = UI.events[ALL_EVENTS]
	if t then
		for frame in pairs(t) do
			if not sent[frame] then
				UI.CallScript(frame, "OnEvent", event, ...)
			end
		end
	end
end

function UI.DumpEvents()
	local f = io.open("events.txt", "w")
	local events = {}
	for event in pairs(UI.events) do
		if event ~= ALL_EVENTS then
			events[#events + 1] = event
		end
	end
	table.sort(events)
	for i, event in ipairs(events) do
		local c = 0
		for f in pairs(UI.events[event]) do c = c + 1 end
		f:write(string.format("%d\t%s\t%d\n", i, event, c))
	end
	f:close()
end
